/*
 * @lc app=leetcode id=129 lang=cpp
 *
 * [129] Sum Root to Leaf Numbers
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int sumNumbers(TreeNode* root) {
        int sum = 0;
        sumNumbers(root, 0, sum);
        return sum;
    }

    int sumNumbers(TreeNode *node, int val, int& sum) {
        if (!node) {
            return sum;
        }

        val = val * 10 + node->val;
        if (!node->left && !node->right) {
            sum += val;
            return sum;
        }

        sumNumbers(node->left,  val, sum);
        sumNumbers(node->right, val, sum);
        return sum;
    }
};

